<template>
  <div class="faultlibrary-register">
    <div class="faultlibrary-register-header">{{ $t('ibodor.faultLibrary.headTip') }}</div>
    <div class="faultlibrary-register-table">
      <div style="text-align: right;padding: 12px 0 16px;">
        <el-input
          v-model.trim="listQueryPage.faultDesc"
          :placeholder="$t('ibodor.faultLibrary.searchPlaceholder')"
          class="search-input"
          @keyup.enter.native="handlePageJump(1)"
        >
          <!-- <i slot="prefix" class="el-input__icon el-icon-search"></i> -->
          <el-button type="primary" slot="append" @click="handlePageJump(1)">
            {{$t('common.base.search')}}
          </el-button>
        </el-input>
      </div>
      <el-table
        v-table-style
        ref="tableRef"
        v-loading="listLoading"
        header-row-class-name="common-list-table-header__v2"
        :data="page.list"
        stripe
        border
        :class="['bbx-normal-list-box']"
        :height="'calc(100vh - 206px)'"
      >
        <template slot="empty">
          <BaseListForNoData
            v-show="!listLoading"
            :notice-msg="$t('common.base.tip.noData')"
          ></BaseListForNoData>
        </template>
        <template v-for="column in columns">
          <el-table-column
            show-overflow-tooltip
            :align="column.align"
            :key="column.field"
            :label="column.displayName"
            :min-width="column.minWidth"
            :prop="column.field"
            :sortable="column.sortable"
            :width="column.width"
            :fixed="column.fixLeft || false"
          >
            <template slot-scope="scope">
              <template v-if="column.field === 'solution'">
                <div class="link" v-if="scope.row.solutionId" @click="openSolutionDialog(scope.row)">
                  {{ $t('common.base.view') }}
                </div>
              </template>
              <template v-else-if="column.field === 'enterState'">
                <el-tooltip placement="top" v-if="enterStateList[scope.row.enterState]">
                  <div slot="content">
                    {{  enterStateList[scope.row.enterState].name }}
                  </div>
                  <div
                    class="state-tags table-blacklist"
                    :class="{
                      'enter': scope.row.enterState,
                      'not-enter': !scope.row.enterState
                    }">
                    {{ enterStateList[scope.row.enterState].name }}
                  </div>
                  <!-- <base-tags :value="[{tagName: enterStateList[scope.row.enterState].name}]" /> -->
                </el-tooltip>
              </template>
              <template v-else-if="column.field === 'relationTask'">
                <div class="link" v-if="scope.row.relationTaskVO" @click="toTaskDetail(scope.row.relationTaskVO.taskId)">
                  {{ scope.row.relationTaskVO.taskNo }}
                </div>
              </template>
              <template v-else>
                {{
                  $formatFormField(column, scope.row)
                }}
              </template>
            </template>
          </el-table-column>
        </template>
        <el-table-column fixed="right" :label="$t('common.fields.action.displayName')" width="100">
          <template slot-scope="{row}">
            <div class="link" v-if="row.registerButton" @click="editDialogRow(row)">{{$t('faultLibrary.enterFaultTree')}}</div>
          </template>
        </el-table-column>
      </el-table>
      <div
        ref="tableFooterContainer"
        class="table-footer bbx-normal-table-footer-10"
      >
        <div class="list-info">
          <i18n path="common.base.table.totalCount">
            <span place="count" class="level-padding">{{ page.total }}</span>
          </i18n>
        </div>
        <el-pagination
          background
          @current-change="handlePageJump"
          @size-change="handleSizeChange"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          :page-size="page.pageSize"
          :current-page="page.pageNum"
          layout="prev, pager, next, sizes, jumper"
          :total="page.total"
        >
        </el-pagination>
      </div>
    </div>
    <ChooseFaultDetailDialog ref="ChooseFaultDetailDialog"></ChooseFaultDetailDialog>

    <!-- 故障描述弹框 -->
    <!-- <faultDescription v-model="faultDescriptionDialogVisible" :current-fault-description-id="currentFaultDescriptionId"
      :create-fault-data="createFaultData" :faultSource="1" :task="task" @startEnter="startEnter" /> -->

    <!-- 解决方案弹框 -->
    <!-- <FaultSolution v-model="faultSolutionDialogVisible" :current-fault-solution-id="currentFaultSolutionId"
      :create-fault-data="createFaultData" :faultSource="1" :task="task" @startEnter="startEnter" /> -->

    <!-- 新建故障和解决方案结合的弹框 -->
    <FaultCompositeDialog 
      v-model="faultSolutionDialogVisible" 
      :create-fault-data="createFaultData" 
      :faultSource="1" 
      :task="task" 
      :initData="initData"
      @success="startEnter" />
  </div>
</template>

<script>
import Page from '@model/Page';
import { getListData, libraryEnter } from '@src/api/Fault';
import { openTabForTaskView } from '@src/util/business/openTab'
import ChooseFaultDetailDialog from '@src/modules/faultLibrary/components/ChooseFaultDetailDialog.vue';
import AuthUtil from '@src/util/auth';
import { getRootWindow } from '@src/util/dom';
// 故障描述弹框
import FaultDescription from '@src/modules/faultLibrary/components/FaultInformationDialog/FaultDescription';
// 解决方案弹框
import FaultSolution from '@src/modules/faultLibrary/components/FaultInformationDialog/FaultSolution';
import FaultCompositeDialog from '@src/modules/faultLibrary/components/FaultInformationDialog/FaultCompositeDialog.vue';

export default {
  name: 'FaultlibraryRegister',
  components: {
    ChooseFaultDetailDialog,
    FaultDescription,
    // 新建/编辑解决方案
    FaultSolution,
    FaultCompositeDialog
  },
  props: {
    initData: {
      type: Object,
      default: () => ({})
    },
  },
  data() {
    return {
      columns: [{
        field: 'faultDesc',
        fieldName: 'faultDesc',
        displayName: this.$t('common.label.describe'),
        formType: 'text',
      }, {
        field: 'solution',
        fieldName: 'solution',
        displayName: this.$t('faultLibrary.detail.solution'),
        formType: 'solution'
      }, {
        field: 'enterState',
        fieldName: 'enterState',
        displayName: this.$t('common.base.status'),
        formType: 'enterState'
      }, {
        field: 'createName',
        fieldName: 'createName',
        displayName: this.$t('common.base.createUser'),
        formType: 'text'
      }, {
        field: 'createTime',
        fieldName: 'createTime',
        displayName: this.$t('common.base.createTime'),
        formType: 'datetime'
      }, {
        field: 'relationTask',
        fieldName: 'relationTask',
        displayName: this.$t('common.base.relationTask'),
        formType: 'relationTask'
      }],
      enterStateList: [{
        label: 0,
        name: this.$t('ibodor.faultLibrary.enterState.0'),
        class: 'not-entered'
      }, {
        label: 1,
        name: this.$t('ibodor.faultLibrary.enterState.1'),
        class: 'entered'
      }],
      searchKeyword: '',
      listLoading: false,
      page: new Page(),
      listQueryPage: {
        faultDesc: '',
        pageSize: 10, // 每页显示条目
        pageNum: 1, // 当前页数
        total: 0,
      },
      solution: {},
      // 新建/编辑故障描述弹框
      faultDescriptionDialogVisible: false,
      // 当前编辑的故障描述id
      currentFaultDescriptionId: '',
      // 新建/编辑解决方案弹框
      faultSolutionDialogVisible: false,
      // 当前编辑的解决方案id
      currentFaultSolutionId: '',
      // 用于记录新建故障描述和解决方案时一些数据，从列表取得，传给弹框
      createFaultData: {},
      task: {},
      faultRow: {}
    }
  },
  mounted() {
    this.getTableList()
  },
  computed: {
    auth() {
      return this.initData?.auths || {};
    },
    hasFaultEnter() {
      return AuthUtil.hasAuth(this.auth, 'FAULT_REGISTER_ENTER')
    },
  },
  methods: {
    // 页数改变时触发
    handlePageJump(pageNum) {
      this.listQueryPage.pageNum = pageNum;
      this.getTableList();
    },
    handleSizeChange(pageSize) {
      this.listQueryPage.pageSize = pageSize;
      this.listQueryPage.pageNum = 1;
      this.getTableList();
    },
    getTableList() {
      this.listLoading = true;
      getListData(this.listQueryPage).then(res => {
        if (!res.success) return;

        let { list } = res.data;
        if (!list?.length) {
          this.resetPage()
          return
        }
        res.data.pageNum = this.listQueryPage.pageNum
        res.data.pageSize = this.listQueryPage.pageSize
        res.data.total = res.data.totalSize

        this.page.cover(res.data);
      }).catch(() => {
        this.resetPage()
      }).finally(() => {
        this.listLoading = false;
      })
    },
    resetPage() {
      const page = new Page()
      page.pageSize = this.listQueryPage.pageSize
      this.page = page
    },
    toTaskDetail(taskId) {
      openTabForTaskView(taskId)
    },
    openSolutionDialog(row) {
      this.solution = row.solutionVO || {}
      this.$refs.ChooseFaultDetailDialog?.open(this.solution.id)
    },
    async enterFaultlibraryCheck(row) {
      let confirm = await this.$platform.confirm(this.$t('ibodor.faultLibrary.enterFaultlibraryTip'));
      if(!confirm) return

      this.enterFaultlibrary(row)
    },
    editDialogRow(row){
      this.createFaultData = {
        id: row.id,
        objDesc: row.objDesc,
        isStartEntry: true,
        isShowSuperior: true,
        parentId: row.faultId, 
        parentDesc: row.faultDesc,
        solutionId: row.solutionId,
      }

      this.faultSolutionDialogVisible = true;
      
      // if(row.solutionId) {
      //   // 解决方法
      //   this.faultSolutionDialogVisible = true;
      //   this.currentFaultSolutionId = row.solutionId;
      //   this.createFaultData.parentId = row.faultId;
      // }else {
      //   // 故障节点
      //   this.faultDescriptionDialogVisible = true;
      //   this.currentFaultDescriptionId = row.faultId;
      // }

      this.task = {
        id: row?.relationTaskVO?.taskId || '',
        taskNo: row?.relationTaskVO?.taskNo || ''
      }
      this.faultRow = row;
    },
    startEnter() {
      this.enterFaultlibrary(this.faultRow)
    },
    enterFaultlibrary(row) {
      libraryEnter({
        faultId: row.faultId,
        faultEnterState: row.enterState,
        solutionId: row.solutionId,
        solutionEnterState: row.solutionVO?.enterState
      }).then(res => {
        if (!res.success) return this.$message.error(res.message)

        this.$message.success(this.$t('ibodor.faultLibrary.enterSuccess'))
        this.getTableList()

        // 刷新这个工单详情
        const RootWindow = getRootWindow(window);
        const taskId = row.relationTaskVO.taskId;
        const currentTaskTab = RootWindow.frameTabs && RootWindow.frameTabs.find(v => v.id?.includes(taskId));
        const fromId = currentTaskTab?.id;

        if(fromId) this.$platform.refreshTab(fromId);
      })
    }
  },
}
</script>


<style lang="scss" scoped>
.state-tags {
  border-radius: 20px;
  width: 56px;
  line-height: 24px;
  height: 24px;
  color: #909399;
  text-align: center;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  &.enter {
    color: #67C23A;
    background: #F0F9EB;
    border: 1px solid #E1F3D8;
  }
  &.not-enter {
    color: #909399;
    background: #F4F4F5;
    border: 1px solid #E9E9EB;
  }
}
.faultlibrary-register {
  height: 100%;
  overflow: auto;
  padding: 12px;
  .faultlibrary-register-header {
    font-size: 14px;
    color: $color-primary-light-6;
    line-height: 22px;
    padding: 8px 16px;
    background: #ECF5FF;
    margin-bottom: 12px;
    border-radius: 4px;
  }
  .search-input {
    width: auto;
    ::v-deep input {
      width: 280px;
    }
    ::v-deep .el-input-group__append{
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
    }
  }
  &-table {
    background-color: #fff;
    border-radius: 4px;
    padding: 16px 16px 0;
    margin-top: 4px;
    &-toolbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
    }
    .status-tab {
      display: inline-block;
      min-width: 52px;
      max-width: 128px;
      height: 22px;
      line-height: 22px;
      padding: 0 8px;
      font-size: 12px;
      border-radius: 11px;
      text-align: center;
      vertical-align: middle;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      color: #fff;
    }
    .link {
      color: $color-primary-light-6 !important;
      cursor: pointer;
      &:hover {
        text-decoration: underline;
      }
    }
  }
  .faultlibrary-register-selected-count {
    @include fontColor();
    padding: 0 3px;
    width: 15px;
    text-align: center;
    cursor: pointer;
    font-size: 13px;
  }
}
</style>